package com.noahplat.person.service.impl;

import com.noahplat.common.utils.Result;
import com.noahplat.common.utils.StatusCode;
import com.noahplat.person.mapper.EhrsMapper;
import com.noahplat.person.mapper.MedicalRecordMapper;
import com.noahplat.person.pojo.Ehrs;
import com.noahplat.person.pojo.MedicalRecord;
import com.noahplat.person.service.EhrsService;
import com.noahplat.person.service.MedicalRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @ClassName: EhrsServiceImpl
 * @Description: 医疗记录实现类
 * @Author 李景星
 * @Date 2021/3/6
 * @Version 1.0
 */
@Service
public class EhrsServiceImpl implements EhrsService {

    @Autowired
    private EhrsMapper ehrsMapper;
    @Autowired
    private MedicalRecordMapper medicalRecordMapper;

    /**
     * 查询医疗记录
     * @param pid
     * @return
     */
    @Override
    public Result getEhrs(Long pid) {
        //查询医疗记录
        Example ehrsExample = new Example(Ehrs.class);
        ehrsExample.createCriteria().andEqualTo("pid", pid);
        Ehrs ehrs = ehrsMapper.selectOneByExample(ehrsExample);
        //查询就诊记录列表
        List<MedicalRecord> medicalRecords = medicalRecordMapper.getMedicalRecords(pid);

        //如果Ehrs为空，也要正常给前端返回数据，且需要初始化数据库
        if(ObjectUtils.isEmpty(ehrs)){
            Ehrs newEhrs = new Ehrs(pid, "", "", "", "");
            ehrsMapper.insert(newEhrs);
            return new Result(true, StatusCode.OK, "查询成功", newEhrs);
        }
        ehrs.setMedicalRecords(medicalRecords);//将就诊记录封装到医疗记录中
        return new Result(true, StatusCode.OK, "查询成功", ehrs);
    }

    /**
     * 更新医疗记录
     * @param ehrs
     * @return
     */
    @Override
    public Result updateEhrs(Ehrs ehrs) {
        int res = ehrsMapper.updateByPrimaryKeySelective(ehrs);
        if(res > 0){
            return new Result(true, StatusCode.OK, "更新成功");
        }
        return new Result(false, StatusCode.ERROR, "更新失败");
    }
}
